package com.bcxj.apipassenger.interceptor;

import com.bcxj.internalcommon.constant.CommonStatusEnum;
import com.bcxj.internalcommon.constant.TokenConstant;
import com.bcxj.internalcommon.dto.ResponseResult;
import com.bcxj.internalcommon.dto.TokenResult;
import com.bcxj.internalcommon.util.JwtUtils;
import com.bcxj.internalcommon.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * ClassName: JwtInterceptor
 * Package: com.bcxj.apipassenger.interceptor
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/9/24 21:59
 * @Version 1.0
 * @Since 1.0
 */

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public JwtInterceptor(@Autowired StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(request.getServletPath());
        // 1 获取token
        String token = request.getHeader("Authorization");
        log.info("token:{}", token);

        // 2 校验token
/*        boolean flag = true; // 真则表示token解析成功
        String msg = "";
        TokenResult tokenResult = null;
        try {
            tokenResult = JwtUtils.parseToken(token);
        } catch (Exception e) {
            msg = "token invalid";
            flag = false;
        }*/
        boolean flag = true;
        String msg = "";
        TokenResult tokenResult = JwtUtils.checkToken(token);
        if (tokenResult == null) {
            flag = false;
            msg = "token invalid";
        }
        // 2.1 解析失败
        if (!flag) {
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(ResponseResult.fail(msg)));
            return false;
        }

        // 2.2 解析成功，继续3

        // 3 从redis取对应的token，然后比较
        String tokenKey = RedisPrefixUtils.generatorTokenKey(tokenResult.getPhone(), tokenResult.getIdentity(), TokenConstant.ACCESS_TOKEN); // tokenResult 不会为null的
        String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);

        // 3.1. 判断redis获取的token是否为null
        if (StringUtils.isBlank(redisToken)) {
            // 双token刷新
            log.info("token refresh is waiting development");
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(ResponseResult.fail(CommonStatusEnum.TOKEN_EXPIRED)));
            return false;
        }

        // 3.2 不相等，直接返回
        if (!token.trim().equals(redisToken)) {
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(ResponseResult.fail("token invalid")));
            return false;
        }

        // 3.3 相等，返回true

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
